import axios from "axios";
import qs from "qs";
import { normalizeHeaderName } from "../utils";

class RequestBase {
  constructor(config = {}) {
    config.timeout = config.timeout || 5000;
    config.baseURL = config.baseURL || "";
    config.headers = config.headers || {};
    normalizeHeaderName(config.headers, "Content-Type");
    this.config = config;
    this.$httpInstance = axios.create(this.config);
    this.requestInterceptors();
    this.responseInterceptors();
  }

  requestInterceptors() {
    this.$httpInstance.interceptors.request.use(
      config => {
        const contentType = config["headers"]["Content-Type"];
        if (
          config.method === "post" && contentType &&
          contentType.indexOf("x-www-form-urlencoded") !==-1
        ) {
          config.data = qs.stringify(config.data);
        }

        return config;
      },
      error => {
        return Promise.reject(error.message);
      }
    );
  }

  responseInterceptors() {
    this.$httpInstance.interceptors.response.use(
      res => {
        return res;
      },
      error => {
        return Promise.reject(error.message);
      }
    );
  }

  get(params) {
    return this.$httpInstance.get(params);
  }

  post(url, params) {
    return this.$httpInstance.post(url, params);
  }
}

export default RequestBase;
